import db from '../utils/dbconf';
import makeres from '../utils/res';
import { TargetDataNoneError } from '../utils/classModal';

export const TABLE_NAME = 'auth_dict';
export const CONF_TABLE_NAME = 'auth_conf';

export default {
	crud: async ({ method, params: { id }, body: data }, res) => {
		delete data.createtime;
		delete data.updatetime;
		let ok;
		switch (method) {
			case 'GET':
				if (!Number(id)) id = ['EXP', 'IS NOT NULL']; // 查询全部
				const auth = await db.table(TABLE_NAME).where({ id, inuse: 1 }).order('weight').select();
				for (let item of auth) {
					const price = await db.table(CONF_TABLE_NAME).where({ auth_id: item.id }).select();
					Object.assign(item, { price });
				}
				return res.send(makeres.success(auth));
			case 'POST':
				id = await db.table(TABLE_NAME).add(data);
				return res.send(makeres.success({ id }));
			case 'PUT':
				ok = await db.table(TABLE_NAME).where({ id }).update(data);
				if (!ok) throw new TargetDataNoneError();
				return res.send(makeres.putsuccess());
			case 'DELETE':
				console.log('====================', id);
				ok = await db.table(TABLE_NAME).where({ id }).delete();
				if (!ok) throw new TargetDataNoneError();
				return res.send(makeres.deletesuccess());
			default:
				throw new Error('None!');
		}
	},
	confcrud: async ({ method, params: { id }, body: data }, res) => {
		delete data.createtime;
		delete data.updatetime;
		let ok;
		switch (method) {
			case 'POST':
				id = await db.table(CONF_TABLE_NAME).add(data);
				return res.send(makeres.success({ id }));
			case 'PUT':
				ok = await db.table(CONF_TABLE_NAME).where({ id }).update(data);
				if (!ok) throw new TargetDataNoneError();
				return res.send(makeres.putsuccess());
			case 'DELETE':
				ok = await db.table(CONF_TABLE_NAME).where({ id }).delete();
				if (!ok) throw new TargetDataNoneError();
				return res.send(makeres.deletesuccess());
			default:
				throw new Error('None!');
		}
	},
};
